#!/usr/bin/env bash
#用法 ./doc/build.md

CORDOVA_PATH=$( cd "$( dirname "$0" )" && pwd -P)
echo "build"
#参数获取
INDEX=0
for param in $*
do
  # echo $INDEX "--" $param
  array[$INDEX]=$param
  INDEX=$[ $INDEX+1 ]
done

PROJECT_PATH=${array[0]}
schemeTarget=${array[1]}
uuid=${array[3]}



cd "$PROJECT_PATH"

if [ -z "$PROJECT_PATH" ]; then
  echo "请输入项目路径"
  exit
fi

if [ -z "$schemeTarget" ]; then
  echo "如果项目是workspace时，请输入scheme;如果项目是project时，请输入target"
  exit
fi

CONFIGURATION=Debug
EMULATOR=1
deviceEmulator=--emulator
if [ -n "${array[2]}" ]; then
  EMULATOR=0
  CONFIGURATION=Release
fi

source "$CORDOVA_PATH/check_reqs"

# 判断是否存在workspace 并获取相应的项目信息
if [ ! $( ls "$PROJECT_PATH" | grep .xcworkspace  ) ]; then
  #项目名称
  XCODEPROJ=$( ls "$PROJECT_PATH" | grep .xcodeproj  )
  PROJECT_NAME=$(basename "$XCODEPROJ" .xcodeproj)
else
  #获取项目空间相应信息
  XCWORKSPACE=$( ls "$PROJECT_PATH" | grep .xcworkspace  )
  XCWORKSPACE_NAME=$(basename "$XCWORKSPACE" .xcworkspace)
fi

if [ ! $( ls "$PROJECT_PATH" | grep .xcworkspace  ) ]; then
  #下面为对工程的编译
  if (( $EMULATOR )); then
    exec xcodebuild -project "$PROJECT_NAME.xcodeproj" -arch i386 -target "$schemeTarget" -configuration $CONFIGURATION -sdk iphonesimulator build VALID_ARCHS="i386" CONFIGURATION_BUILD_DIR="$PROJECT_PATH/build/emulator"
  else
    exec xcodebuild -xcconfig "$CORDOVA_PATH/build.xcconfig" -project "$PROJECT_NAME.xcodeproj" ARCHS="armv7 armv7s arm64" -target "$schemeTarget" -configuration $CONFIGURATION -sdk iphoneos build VALID_ARCHS="armv7 armv7s arm64" CONFIGURATION_BUILD_DIR="$PROJECT_PATH/build/device" PROVISIONING_PROFILE=$uuid
  fi
else
  # 以下为对项目空间的编译
  if (( $EMULATOR )); then
    exec xcodebuild -workspace "$XCWORKSPACE_NAME.xcworkspace" -arch i386 -scheme $schemeTarget  -configuration $CONFIGURATION -sdk iphonesimulator build VALID_ARCHS="i386" CONFIGURATION_BUILD_DIR="$PROJECT_PATH/build/emulator"
  else
    exec xcodebuild -xcconfig "$CORDOVA_PATH/build.xcconfig" -workspace "$XCWORKSPACE_NAME.xcworkspace" ARCHS="armv7 armv7s arm64" -scheme "$schemeTarget" -configuration $CONFIGURATION -sdk iphoneos build VALID_ARCHS="armv7 armv7s arm64" CONFIGURATION_BUILD_DIR="$PROJECT_PATH/build/device" PROVISIONING_PROFILE=$uuid
    
  fi
fi
